package nuist.hanniko.stu.webbackend.service.cmd_runner;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import nuist.hanniko.stu.webbackend.dao.mapper.HistoryRecordMapper;
import nuist.hanniko.stu.webbackend.dao.redis.RealTimeRecordDAO;
import nuist.hanniko.stu.webbackend.model.LwM2m.LwM2MResourceValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Component
@Order(value = 3)
public class AutoUploadPersistenceService implements CommandLineRunner {

    private final static Logger LOG = LoggerFactory.getLogger(AutoUploadPersistenceService.class);

    private final RealTimeRecordDAO realTimeRecordDAO;

    private final HistoryRecordMapper historyRecordMapper;

    @Autowired
    public AutoUploadPersistenceService(RealTimeRecordDAO realTimeRecordDAO, HistoryRecordMapper historyRecordMapper) {
        this.realTimeRecordDAO = realTimeRecordDAO;
        this.historyRecordMapper = historyRecordMapper;
    }

    @Override
    public void run(String... args) throws Exception {
        LOG.info("-------- Redis持久化任务 - 启动 --------");
    }

    @Scheduled(fixedRate = 100 * 1000)
    private void uploadData() {
        JSONArray data = realTimeRecordDAO.getAllData();
        List<LwM2MResourceValue> insertList = new ArrayList<>();

        for (JSONArray array : data.toJavaList(JSONArray.class)) {
            for (JSONObject record : array.toJavaList(JSONObject.class)) {
                LwM2MResourceValue resourceValue = new LwM2MResourceValue(
                        record.getString("device_id"),
                        record.getString("object_id"),
                        record.getString("resource_id"),
                        record.getString("value_type"),
                        record.getString("value"),
                        new Date(record.getTimestamp("timestamp").getTime())
                );
                insertList.add(resourceValue);
            }
        }

        LOG.info("Scheduled Upload task, record count: {}", insertList.size());

        if (!insertList.isEmpty()) {
            historyRecordMapper.insertBatch(insertList);
        }
    }
//
//    @Scheduled(fixedRate = 30 * 60 * 1000)
//    private void uploadErr() {
//
//    }
}
